package com.supermarket.controller;

import cn.hutool.core.io.FileUtil;
import com.supermarket.common.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileController {

    @Value("${file.upload.path:uploads}")
    private String uploadPath;

    @Value("${file.upload.maxSize:5242880}")
    private long maxFileSize; // 默认5MB

    /**
     * 通用文件上传
     *
     * @param file 上传的文件
     * @return 返回文件访问URL
     */
    @PostMapping
    public ResponseResult<Map<String, String>> upload(@RequestParam("file") MultipartFile file) {
        return uploadFile(file, uploadPath);
    }

    /**
     * 商品图片上传专用接口
     *
     * @param file 上传的商品图片文件
     * @return 返回商品图片访问URL
     */
    @PostMapping("/commodity")
    public ResponseResult<Map<String, String>> uploadCommodityImage(@RequestParam("file") MultipartFile file) {
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !(contentType.equals(MediaType.IMAGE_JPEG_VALUE) 
                || contentType.equals(MediaType.IMAGE_PNG_VALUE))) {
            return ResponseResult.error(400, "商品图片只能是JPG或PNG格式");
        }
        
        // 验证文件大小
        if (file.getSize() > maxFileSize) { // 5MB限制
            return ResponseResult.error(400, "商品图片大小不能超过5MB");
        }
        
        try {
            // 生成唯一文件名
            String fileName = "commodity_" + UUID.randomUUID() + "_" + file.getOriginalFilename();
            
            // 确保目录存在
            String commodityPath = uploadPath + "/commodity";
            Path dirPath = Paths.get(commodityPath);
            Files.createDirectories(dirPath);
            
            // 保存文件
            Path filePath = Paths.get(commodityPath + "/" + fileName);
            FileUtil.writeBytes(file.getBytes(), filePath.toAbsolutePath().toString());
            
            // 生成完整的访问URL
            String fileUrl = "/uploads/commodity/" + fileName;
            
            // 添加日志
            System.out.println("商品图片上传成功: " + fileName);
            System.out.println("访问URL: " + fileUrl);
            
            return ResponseResult.success(Map.of("url", fileUrl));
        } catch (IOException e) {
            System.out.println("商品图片上传失败: " + e.getMessage());
            return ResponseResult.error(500, "商品图片上传失败: " + e.getMessage());
        }
    }

    /**
     * 头像上传专用接口
     *
     * @param file 上传的头像文件
     * @param username 用户名(可选)
     * @return 返回头像访问URL
     */
    @PostMapping("/avatar")
    public ResponseResult<String> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "username", required = false) String username) {
        
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !(contentType.equals(MediaType.IMAGE_JPEG_VALUE) 
                || contentType.equals(MediaType.IMAGE_PNG_VALUE))) {
            return ResponseResult.error(400, "头像只能是JPG或PNG格式");
        }
        
        // 验证文件大小
        if (file.getSize() > maxFileSize) { // 5MB限制
            return ResponseResult.error(400, "头像大小不能超过5MB");
        }
        
        // 使用用户名作为文件名前缀（如果提供）
        String fileName = (StringUtils.hasText(username) ? username + "_" : "") 
                + UUID.randomUUID() + "_" + file.getOriginalFilename();
        
        try {
            // 确保目录存在
            String avatarPath = uploadPath + "/avatars";
            Path dirPath = Paths.get(avatarPath);
            Files.createDirectories(dirPath);
            
            // 保存文件
            Path filePath = Paths.get(avatarPath + "/" + fileName);
            FileUtil.writeBytes(file.getBytes(), filePath.toAbsolutePath().toString());
            
            // 生成完整的访问URL
            String fileUrl = "/uploads/avatars/" + fileName;
            
            // 添加更详细的调试日志
            System.out.println("======== 头像上传信息 ========");
            System.out.println("文件原始名称: " + file.getOriginalFilename());
            System.out.println("文件类型: " + contentType);
            System.out.println("文件大小: " + (file.getSize() / 1024) + "KB");
            System.out.println("保存的文件名: " + fileName);
            System.out.println("文件本地路径: " + filePath.toAbsolutePath());
            System.out.println("访问URL: " + fileUrl);
            System.out.println("==============================");
            
            return ResponseResult.success(fileUrl);
        } catch (IOException e) {
            System.out.println("文件上传失败: " + e.getMessage());
            e.printStackTrace(); // 打印完整堆栈信息以便调试
            return ResponseResult.error(500, "头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 获取文件
     *
     * @param fileName 文件名
     * @return 文件内容
     */
    @GetMapping("/{fileName:.+}")
    public ResponseResult<byte[]> getFile(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(uploadPath + "/" + fileName);
            if (!Files.exists(filePath)) {
                return ResponseResult.error(404, "文件不存在");
            }
            
            byte[] fileContent = Files.readAllBytes(filePath);
            return ResponseResult.success(fileContent);
        } catch (IOException e) {
            return ResponseResult.error(500, "获取文件失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名
     * @return 删除结果
     */
    @DeleteMapping("/{fileName:.+}")
    public ResponseResult<Boolean> deleteFile(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(uploadPath + "/" + fileName);
            if (!Files.exists(filePath)) {
                return ResponseResult.error(404, "文件不存在");
            }
            
            boolean deleted = Files.deleteIfExists(filePath);
            if (deleted) {
                return ResponseResult.success(true);
            } else {
                return ResponseResult.error(500, "删除文件失败");
            }
        } catch (IOException e) {
            return ResponseResult.error(500, "删除文件失败: " + e.getMessage());
        }
    }

    /**
     * 通用文件上传辅助方法
     */
    private ResponseResult<Map<String, String>> uploadFile(MultipartFile file, String targetPath) {
        try {
            // 验证文件大小
            if (file.getSize() > maxFileSize) {
                return ResponseResult.error(400, "文件大小超过限制: " + (maxFileSize / 1024 / 1024) + "MB");
            }
            
            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            Path path = Paths.get(targetPath + "/" + fileName);
            
            // 确保目录存在
            Files.createDirectories(path.getParent());
            
            // 保存文件
            FileUtil.writeBytes(file.getBytes(), path.toAbsolutePath().toString());
            
            return ResponseResult.success(Map.of("url", "/uploads/" + fileName));
        } catch (IOException e) {
            return ResponseResult.error(500, "文件上传失败: " + e.getMessage());
        }
    }
}
